package com.hitqz.robot.biz.autoInit;

import cn.hutool.extra.spring.SpringUtil;
import com.hitqz.robot.api.business.enums.WorkStatusEnum;
import com.hitqz.robot.api.common.dto.tickets.CtrlTicketsEvent;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.biz.flow.util.LiteFlowUtil;
import com.hitqz.robot.biz.service.RobotService;
import com.yomahub.liteflow.spi.holder.CmpAroundAspectHolder;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


/**
 * @author xupkun
 * @date 2024/5/30
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AppRunner implements CommandLineRunner {

    private final RobotService robotService;

    @Override
    public void run(String... args) {
        CmpAroundAspectHolder.loadCmpAroundAspect();
        try {
            Robot robot = robotService.getDefaultRobot();
            //这里属于程序重启，工作状态给他改成空闲，避免上次是工作中关的程序，后续任务无法启动
            robot.setOnlineStatus("0");
            robot.setWorkStatus(WorkStatusEnum.FREE.getCode());
            robotService.updateById(robot);
            log.info("机器人后台启动，工作状态切为空闲");
            SpringUtil.getApplicationContext().publishEvent(robot);
        }catch (Exception e){
            log.error("初始化失败",e);
        }
    }


    @PreDestroy
    public void preDestroy() {
        log.info("机器人后台即将关闭，保存信息,暂停导航");
        Robot robot = robotService.getDefaultRobot();
        robot.setOnlineStatus("0");
        robot.setWorkStatus(WorkStatusEnum.FREE.getCode());
        robotService.updateById(robot);
        // 暂停工单任务，
        CtrlTicketsEvent ctrlTicketsEvent = new CtrlTicketsEvent();
        ctrlTicketsEvent.setType(CtrlTicketsEvent.TYPE_PAUSE);
        ctrlTicketsEvent.setMessage("系统重启,任务暂停");
        ctrlTicketsEvent.setTicketsId(LiteFlowUtil.ticketsId);
        SpringUtil.getApplicationContext().publishEvent(ctrlTicketsEvent);
    }


}
